package com.dms.modules.user.controller;

import com.dms.common.api.ApiResponse;
import com.dms.common.security.JwtTokenProvider;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.user.dto.*;
import com.dms.modules.user.vo.LoginResponse;
import com.dms.modules.user.vo.UserInfoVO;
import com.dms.modules.user.entity.User;
import com.dms.modules.user.service.UserService;
import com.dms.modules.user.service.UserCenterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.List;

@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/user")
@Api(tags = "用户接口")
public class UserController extends BaseUserController<User, UserService> {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private UserCenterService userCenterService;
    
    @Autowired
    private UserService userService;

    @Override
    protected UserService getService() {
        return userService;
    }

    @PostMapping("/auth/login")
    @ApiOperation(value = "用户登录", notes = "使用用户名和密码进行登录认证,返回JWT token")
    public ApiResponse<LoginResponse> login(@RequestBody @Validated UserLoginDTO loginDTO) {
        log.info("用户登录请求: {}", loginDTO.getUsername());
        try {
            User user = userService.login(loginDTO);
            String token = jwtTokenProvider.generateToken(user);
            LoginResponse response = new LoginResponse();
            response.setToken(token);
            response.setUser(user);
            return ApiResponse.success(response);
        } catch (Exception e) {
            log.error("登录失败: {}", e.getMessage(), e);
            return ApiResponse.businessFailed(e.getMessage());
        }
    }

    @PostMapping("/auth/logout")
    @ApiOperation(value = "用户登出", notes = "用户登出系统")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Void> logout() {
        try {
            // 清除当前用户的认证信息
            org.springframework.security.core.context.SecurityContextHolder.clearContext();
            log.info("用户登出成功");
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("用户登出失败: {}", e.getMessage(), e);
            return ApiResponse.businessFailed("登出失败，请稍后重试");
        }
    }

    @PostMapping("/auth/register")
    @ApiOperation(value = "用户注册", notes = "注册新用户")
    public ApiResponse<Long> register(@RequestBody @Validated UserRegisterDTO registerDTO) {
        log.info("用户注册请求: {}", registerDTO.getUsername());
        try {
            Long userId = userCenterService.register(registerDTO);
            return ApiResponse.success(userId);
        } catch (Exception e) {
            log.error("注册失败: {}", e.getMessage(), e);
            return ApiResponse.businessFailed(e.getMessage());
        }
    }

    @PostMapping("/auth/verify-code")
    @ApiOperation(value = "发送验证码", notes = "发送手机验证码")
    public ApiResponse<Void> sendVerifyCode(
            @RequestParam @NotBlank(message = "手机号不能为空") 
            @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") String phone,
            @RequestParam(defaultValue = "1") Integer type) {
        log.info("发送验证码请求: phone={}, type={}", phone, type);
        try {
            userCenterService.sendVerifyCode(phone, type);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("发送验证码失败: {}", e.getMessage(), e);
            return ApiResponse.businessFailed(e.getMessage());
        }
    }

    @GetMapping("/role/{roleId}/users")
    @ApiOperation(value = "获取指定角色的用户列表", notes = "根据角色ID获取对应的用户列表")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<List<User>> getUserListByRole(@PathVariable("roleId") Long roleId) {
        List<User> userList = userService.getUserListByRoleId(roleId);
        return ApiResponse.success(userList);
    }

    @PutMapping("/status/{userId}")
    @ApiOperation(value = "更新用户状态", notes = "启用或禁用用户账号")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Boolean> updateUserStatus(
            @PathVariable("userId") Long userId,
            @RequestParam("status") Integer status) {
        log.info("更新用户状态: userId={}, status={}", userId, status);
        try {
            boolean result = userService.updateUserStatus(userId, status);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("更新用户状态失败", e);
            return ApiResponse.businessFailed(e.getMessage());
        }
    }

    @GetMapping("/profile")
    @ApiOperation("获取用户信息")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<UserInfoVO> getUserInfo() {
        Long userId = SecurityUtils.getCurrentUserId();
        UserInfoVO userInfo = userCenterService.getUserInfo(userId);
        return ApiResponse.success(userInfo);
    }

    @PutMapping("/profile")
    @ApiOperation("更新用户信息")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Void> updateUserInfo(@RequestBody @Validated UserProfileDTO profileDTO) {
        Long userId = SecurityUtils.getCurrentUserId();
        userCenterService.updateUserProfile(userId, profileDTO);
        return ApiResponse.success();
    }

    @PutMapping("/password")
    @ApiOperation("修改密码")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Void> changePassword(
            @RequestParam @NotBlank(message = "原密码不能为空") String oldPassword,
            @RequestParam @NotBlank(message = "新密码不能为空") String newPassword) {
        Long userId = SecurityUtils.getCurrentUserId();
        UpdatePasswordDTO updatePasswordDTO = new UpdatePasswordDTO();
        updatePasswordDTO.setOldPassword(oldPassword);
        updatePasswordDTO.setNewPassword(newPassword);
        userCenterService.updatePassword(userId, updatePasswordDTO);
        return ApiResponse.success();
    }

    @PostMapping("/avatar")
    @ApiOperation("上传头像")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        Long userId = SecurityUtils.getCurrentUserId();
        String avatarUrl = userService.uploadAvatar(userId, file);
        return ApiResponse.success(avatarUrl);
    }

    @DeleteMapping("/avatar")
    @ApiOperation("删除头像")
    @PreAuthorize("isAuthenticated()")
    public ApiResponse<Void> deleteAvatar() {
        Long userId = SecurityUtils.getCurrentUserId();
        userService.deleteAvatar(userId);
        return ApiResponse.success();
    }
} 